<?php
namespace Modules\User\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\User\Entities\User;

use Modules\Core\Helpers\HttpClient;

use Validator;
use ThrowException;
use Auth;
use DB;
use Cache;
use Miniapp;
use ByteDance;
use Setting;
use SMS;

use AppleSignIn\ASDecoder;

// App上使用的登陆
class AppController extends Controller
{
    public function loginWithWechat(Request $req)
    {
        $rule = [
            // 'openid' => ['required'],
            // 'access_token' => ['required'],
            // 'code' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        // 手机号简单验证
        if ($req->input('phone')) {
            if (strlen($req->phone) !== 11) {
                ThrowException::Conflict('手机号格式不正确~');
            }
        }

        $phone = $req->input('phone');
        $phoneCode = $req->input('phone_code');

        // 如果有data_uuid，则直接从缓存中读取而不使用授权信息读取
        if ($req->input('data_uuid')) {
            $data = Cache::get('login_data_' . $req->data_uuid);
        }
        else {
            $http = new HttpClient();
            $token  = $req->access_token;
            $openid = $req->openid;
            $data = $http->get('https://api.weixin.qq.com/sns/userinfo?access_token=' . $token  . '&openid=' . $openid);
            $data = @json_decode($data, true);
        }

        // \Log::error($data);

        if (!@$data['unionid']) {
            ThrowException::Conflict('授权信息失效~');
        }

        // 有手机号
        if ($phone) {
            if ($phone !== @Setting::get('sys_preset_account')['phone'] 
                || $phoneCode !== @Setting::get('sys_preset_account')['phone_code']) 
            {
                SMS::verifyCode($phone, $phoneCode, 'login') || ThrowException::Conflict('验证码不正确');
            }
            
            $data['phone'] = $phone;
        }

        DB::beginTransaction();

        $openidType = 'miniapp';
        
        list($user, $isCreated) = User::findOrCreateByApp($data, Auth::clientName(), $openidType);

        // 没有找到用户并且没有创建新用户
        if (!$user) {
            $dataUuid = uniqid();
            Cache::put('login_data_' . $dataUuid, $data, 300);

            return [
                'data_uuid' => $dataUuid,
                'is_need_phone' => 1
            ];
        } 

        // 绑定邀请人
        if ($req->input('inviter') && $isCreated) {
            $inviter = User::getEntity([
                'uuid' => $req->inviter
            ], false);

            $user->bindInviter($inviter, $req);
        }

        DB::commit();

        $token = Auth::generateToken($user);

        return [
            'token' => $token,
            'is_first_login' => $isCreated ? 1 : 0
        ];
    }
    

    // H5手机号登陆
    public function loginWithPhoneCode(Request $req)
    {
        $rule = [
            'phone' => ['required', 'size:11'],
            'phone_code' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        // 手机号简单验证
        if ($req->input('phone')) {
            if (strlen($req->phone) !== 11) {
                ThrowException::Conflict('手机号格式不正确~');
            }
        }

        \Log::error('APP 手机号验证码登陆');
        \Log::error($req->all());
        \Log::error($req->phone);
        $phone = $req->phone;
        // 校验验证码是否正确
        if ($phone !== @Setting::get('sys_preset_account')['phone'] || $req->phone_code !== @Setting::get('sys_preset_account')['phone_code']) {
            SMS::verifyCode($req->phone, $req->phone_code, 'login') || ThrowException::Conflict('验证码不正确');
        }

        // 是否已绑定微信
        $isBindWechat = false;
        // 是否创建
        $isCreated = false;
        
        DB::beginTransaction();

        $user = User::where('phone', $phone)->first();

        if (!$user) {

            // 创建用户
            $user = User::createWithPhone($phone);

            $isCreated = true;
        }

        // 绑定邀请人
        if ($req->input('inviter') && $isCreated) {
            $inviter = User::getEntity([
                'uuid' => $req->inviter
            ], false);

            $user->bindInviter($inviter);
        }

        DB::commit();

        $token = Auth::generateToken($user);

        return [
            'token' => $token,
            'is_first_login' => $isCreated ? 1 : 0,
            'is_bind_wechat' => $isBindWechat ? 1 : 0
        ];
    }

    // App上使用
    public function loginWithAppleId(Request $req)
    {
        $rule = [
            // 'identity_token' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        // 如果有data_uuid，则直接从缓存中读取而不使用授权信息读取
        if ($req->input('data_uuid')) {
            $data = Cache::get('login_data_' . $req->data_uuid);
        }
        else {
            $identityToken = $req->identity_token;
            $appleSignInPayload = ASDecoder::getAppleSignInPayload($identityToken);

            $email = $appleSignInPayload->getEmail();
            $appleId = $appleSignInPayload->getUser();

            if (!$appleId) {
                ThrowException::Conflict('授权失效~');
            }

            $data = [
                'email' => $email,
                'apple_id' => $appleId
            ];
        }


        \Log::error('APP 手机号验证码登陆 loginWithAppleId');
        \Log::error($data);
        \Log::error($req->all());
        \Log::error($req->phone);
        \Log::error('$appleId:'.$appleId);
        \Log::error('$email:'.$email);

//        $is_tourist = $req->input('is_tourist');
//        if ( $is_tourist == 1 ){
//            // 游客登陆
//
//        }else{
//
//        }

        // 有手机号
        $phone = $req->input('phone');
        $phoneCode = $req->input('phone_code');
        if ($phone) {
            SMS::verifyCode($phone, $phoneCode, 'login') || ThrowException::Conflict('验证码不正确');
            $data['phone'] = $phone;
        }

        DB::beginTransaction();

        $openidType = 'miniapp';
        
        list($user, $isCreated) = User::findOrCreateByAppleId($data, Auth::clientName(), $openidType);

        // 没有找到用户并且没有创建新用户
        if (!$user) {
            $dataUuid = uniqid();
            Cache::put('login_data_' . $dataUuid, $data, 300);

            return [
                'data_uuid' => $dataUuid,
                'is_need_phone' => 1
            ];
        } 

        // 绑定邀请人
        if ($req->input('inviter') && $isCreated) {
            $inviter = User::getEntity([
                'uuid' => $req->inviter
            ], false);

            $user->bindInviter($inviter, $req);
        }

        DB::commit();

        $token = Auth::generateToken($user);

        return [
            'token' => $token,
            'is_first_login' => $isCreated ? 1 : 0
        ];
    }

    // 游客登录
    public function loginWithTourist(Request $req)
    {
        $rule = [
             'app_id' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

//        \Log::error('APP 游客登录登陆 loginWithTourist');

        $app_id = $req->input('app_id');

        // 是否创建
        $isCreated = false;

        DB::beginTransaction();

        $user = User::where('apple_id', $app_id)->first();

        if (!$user) {

            // 创建用户
            $user = User::createWithAppleID($app_id);

            $isCreated = true;
        }

        DB::commit();

        $token = Auth::generateToken($user);

        return [
            'token' => $token,
            'is_first_login' => $isCreated ? 1 : 0,
        ];
    }


    // bind wechat  绑定微信
    public function bindWechat(Request $req)
    {
        $rule = [
            'openid' => ['required'],
            'access_token' => ['required'],
            // 'code' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $http = new HttpClient();
        $token  = $req->access_token;
        $openid = $req->openid;
        $data = $http->get('https://api.weixin.qq.com/sns/userinfo?access_token=' . $token  . '&openid=' . $openid);
        $data = @json_decode($data, true);

        $openId = @$data['openId'] ?: @$data['openid'];
        $unionId = @$data['unionId'] ?: @$data['unionid'];
        $openidType = 'app';
        $clientName = 'default';

        // 绑定
        $where = [
            'openid' => $openId,
            'openid_type' => $openidType,
            'client_name' => $clientName,
        ];

        $user->update([
            'name' => @$data['nickname'] ?: $user->name,
            'headimg' =>  @$data['headimgurl']
        ]);

        // 创建openid 记录
        if (!$user->wechats()->where($where)->first()) {
            $user->wechats()->create([
                'uuid' => uniqid(),
                'openid' => $openId,
                'unionid' => $unionId,
                'headimgurl' => $data['headimgurl'],
                'nickname' => $data['nickname'],
                'openid_type' => $openidType,
                'client_name' => $clientName,
                'type' => 'wechat'
            ]);
        }

        return [
        ];
    }

}
